<?php

if (function_exists('date_default_timezone_set')) {
	date_default_timezone_set('Asia/Shanghai');
}

function updateTime ($database, $user, $type) {
	$res = $database->query("SELECT `id` FROM cfg_update_time where `companyId` = {$user['companyId']} and `type` = {$type} and `username` = '{$user['username']}' LIMIT 1");
	if(isset($res[0]['id'])){
		$database->query("UPDATE cfg_update_time SET datetime = now() WHERE id = '{$res[0]['id']}';");
	} else {
		$database->query("INSERT INTO cfg_update_time (`companyId`, `type`, `username`, `datetime`)  VALUES ('{$user['companyId']}', {$type}, '{$user['username']}', now() );");
	}
}

function getProfessionalReportId($header) {
	$HttpPost = HttpPost('https://api.baidu.com/json/sms/service/ReportService/getProfessionalReportId', $header);
	if( !$HttpPost ) {
		return ['code'=> 403, 'data'=> 'network anomaly detection.' ] ;
	}
	$jsonDecode = json_decode($HttpPost);
	if(!isset($jsonDecode->header->desc)){
		return ['code'=> 403, 'data'=> 'network anomaly detection.' ] ;
	}
	if( $jsonDecode->header->desc == 'failure') {
		return ['code'=> 403, 'data'=> $jsonDecode->header->failures[0]->code . ' - ' . $jsonDecode->header->failures[0]->message];
	}
	if( !isset($jsonDecode->body->data[0])) {
		return ['code'=> 403, 'data'=> 'network anomaly detection.' ] ;
	}
	return ['code'=> 0, 'data'=> $jsonDecode->body->data[0] ] ;
}

function getReportFileUrl ($array, $reportId) {
	$reportCount = 0;
	$reportFilePath = '';
	while (!$reportFilePath) {
		$reportCount++;
		if($reportCount == 10) {
			break;
		}
	  $header = json_encode ( [ 'header'=> [ 'username'=> $array['username'], 'password'=> $array['password'], 'token'=> $array['token'] ], 'body'=> ['reportId'=> $reportId ] ] );
		$HttpPost = HttpPost('https://api.baidu.com/json/sms/service/ReportService/getReportFileUrl', $header);
		if( $HttpPost ) {
			$jsonDecode = json_decode($HttpPost);
			if( isset($jsonDecode->header->desc) && $jsonDecode->header->desc == 'success') {
				$reportFilePath = $jsonDecode->body->data[0]->reportFilePath;
			}
		}
		usleep(1000000);
	}
	return $reportFilePath;
}

function getReportFiles($reportFilePath) {
	$HttpGet = HttpGet($reportFilePath);
	if(!$HttpGet) {
		return false;
	}
	$stdData = iconv("GB2312", "UTF-8//IGNORE", trim($HttpGet));
	if(!$stdData) {
		return false;
	}
	$stdData = str_replace(["\\", "'", ','], ['','',''], $stdData);
	$result = explode("\n", $stdData);
	if( count($result) == 1 ) {
		return false;
	}
	return $result;
}

function HttpPost($url, $data) {
	$ch = curl_init ();
	curl_setopt ( $ch, CURLOPT_URL, $url );
	curl_setopt ( $ch, CURLOPT_POST, true );
	curl_setopt ( $ch, CURLOPT_HEADER, false);
	curl_setopt ( $ch, CURLOPT_POSTFIELDS, $data );
	curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, true );
	curl_setopt ( $ch, CURLOPT_SSL_VERIFYPEER, false );
	curl_setopt ( $ch, CURLOPT_SSL_VERIFYHOST, false );
	curl_setopt ( $ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json; charset=utf-8'] );
	$string = curl_exec ( $ch );
	curl_close ($ch );
	return $string;
}

function HttpGet($url) {
	$curl = curl_init();
	curl_setopt($curl, CURLOPT_URL, $url);
	curl_setopt($curl, CURLOPT_HEADER, false);
	curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
	curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
	curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
	$string = curl_exec($curl);
	curl_close($curl);
	return $string;
}

function cashPrice($term, $price ) {
	if( $term <= 0 ) {
		return $price;
	}
	$result = round($price / $term, 2);
	return $result;
}

function getConfig() {
	$config = parse_ini_file('database.env', true) ?: [];
	return [
		'host' => $config['DATABASE']['HOSTNAME'],
		'port' => $config['DATABASE']['HOSTPORT'],
		'user' => $config['DATABASE']['USERNAME'],
		'password' => $config['DATABASE']['PASSWORD'],
		'database' => $config['DATABASE']['DATABASE'],
		'charset' => $config['DATABASE']['CHARSET'],
		'curlnumber' => $config['DATABASE']['CURLNUMBER']
	];
}

function showMessage($message) {
	echo '【'.date('Y-m-d H:i:s').'】' . $message . "\n";
}

function getArrayValue( $input, $needle, $column_key, $result, $default = 'null' ) {
	if(!is_array($input)) {
		return $default;
	}
	$index = array_search($needle, array_column($input, $column_key));
	if( $index === false ) {
		return $default;
	}
	return $input[$index][$result];
}

function getArray( $input, $needle, $column_key) {
	$index = array_search($needle, array_column($input, $column_key));
	if( $index === false ) {
		return false;
	}
	return $input[$index];
}